<template>
  <view class="table-card">
    <!-- 标题 -->
    <view class="table-header">
      <view class="title-section">
        <view v-if="!return_proj_list" class="table-title">项目列表</view>
        <view v-else class="table-title">审批工单</view>
        <!-- 搜索框 -->
        <view class="search-container">
          <input
            v-model="searchKeyword"
            placeholder="搜索项目名称、MIS编码、站点名称..."
            class="search-input"
            @input="onSearchInput"
          />
          <view class="search-icon">🔍</view>
        </view>
      </view>
      <!-- 筛选：区县公司 -->
      <view class="filter-group">
        <text class="filter-label">区县公司：</text>
        <picker
          mode="selector"
          :range="companyOptions"
          :value="selectedCompanyIndex"
          @change="onFilterChange"
          class="filter-picker"
        >
          <view class="picker-display">
            {{ companyOptions[selectedCompanyIndex] }}
          </view>
        </picker>
        <button
          class="approval-btn"
          @click="fetchTableData"
          v-if="return_proj_list"
        >
          项目列表
        </button>
        <button
          class="approval-btn"
          @click="fetchApprovalData"
          v-else-if="role == 'rose2' || role == 'rose3'"
        >
          审批工单
          <view class="badge" v-if="approvalCount >= 0 && role != 'rose3'">{{
            approvalCount
          }}</view>
        </button>
      </view>
    </view>

    <uni-popup ref="approve_modal" type="center">
      <view class="modal-content">
        <view class="modal-title">审批工单处理</view>
        <!-- 审批意见 -->
        <view class="approve-opinion">
          <!-- 添加v-model绑定 -->
          <textarea
            placeholder="请输入审批意见"
            class="approve-input"
            v-model="approveOpinion"
          />
        </view>
        <view class="btn-group">
          <button class="modal-close" @click="approve_accept()">通过</button>
          <button class="modal-close" @click="approve_resuse()">驳回</button>
        </view>
      </view>
    </uni-popup>

    <!-- 项目详情模态框 -->
    <uni-popup ref="detail_modal" type="center">
      <view class="detail-modal-content">
        <view class="detail-modal-header">
          <view class="detail-modal-title">项目详情</view>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </view>
        
        <!-- 选项卡导航 -->
        <view class="detail-tab-nav">
          <view
            v-for="(tab, index) in detailTabs"
            :key="index"
            :class="['detail-tab-item', currentDetailTab === index ? 'active' : '']"
            @click="switchDetailTab(index)"
          >
            {{ tab.title }}
          </view>
        </view>

        <!-- 内容展示区域 -->
        <view class="detail-content">
          <!-- 定额不一致 -->
          <view v-if="currentDetailTab === 0" class="detail-section">
            <view v-if="detailData.overList.length === 0" class="empty-message">
              暂无定额不一致记录
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>定额编码</th>
                    <th>差异类型</th>
                    <th>材料项目</th>
                    <th>标准项目</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.overList" :key="idx">
                    <td>{{ idx + 1 }}</td>
                    <td>
                      <a 
                        href="javascript:void(0)" 
                        @click.stop="previewDeFile(item.de_id)"
                        class="de-code-link"
                      >
                        {{ item.de_id }}
                      </a>
                    </td>
                    <td>{{ item.diffType }}</td>
                    <td>{{ item.wrong }}</td>
                    <td>{{ item.stand }}</td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 用量清单 -->
          <view v-if="currentDetailTab === 1" class="detail-section">
            <view class="highlight-tip">绿色高亮的行表示根据验收情况修改过。高亮深度表示修改次数，单击可跳转并高亮所有相关的历史记录</view>
            <view v-if="detailData.usageList.length === 0" class="empty-message">
              暂无用量清单数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>定额编码</th>
                    <th>定额名称</th>
                    <th>标准用量</th>
                    <th>单位</th>
                    <th>修改次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.usageList" :key="idx" 
                    :class="getHighlightClass(item.acc_mark, getModificationCount(item.id, 'usage'))"
                    @click="item.acc_mark !== 0 && navigateToHistory(item.id, 'usage')">
                    <td>{{ idx + 1 }}</td>
                    <td>
                      <a 
                        href="javascript:void(0)" 
                        @click.stop="previewDeFile(item.de_id)"
                        class="de-code-link"
                      >
                        {{ item.de_id }}
                      </a>
                    </td>
                    <td>{{ item.de_name }}</td>
                    <td>{{ item.standUsage }}</td>
                    <td>{{ item.unit }}</td>
                    <td>
                      <span v-if="item.acc_mark !== 0" class="modification-count">
                        {{ getModificationCount(item.id, 'usage') }}次
                      </span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 机械使用费 -->
          <view v-if="currentDetailTab === 2" class="detail-section">
            <view class="highlight-tip">绿色高亮的行表示根据验收情况修改过。高亮深度表示修改次数，单击可跳转对应的记录</view>
            <view v-if="detailData.machineryFees.length === 0" class="empty-message">
              暂无机械使用费数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>定额编码</th>
                    <th>定额名称</th>
                    <th>标准用量</th>
                    <th>单位</th>
                    <th>修改次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.machineryFees" :key="idx" 
                    :class="getHighlightClass(item.acc_mark, getModificationCount(item.id, 'jx'))"
                    @click="item.acc_mark !== 0 && navigateToHistory(item.id, 'jx')">
                    <td>{{ idx + 1 }}</td>
                    <td>
                      <a 
                        href="javascript:void(0)" 
                        @click.stop="previewDeFile(item.de_id)"
                        class="de-code-link"
                      >
                        {{ item.de_id }}
                      </a>
                    </td>
                    <td>{{ item.de_name }}</td>
                    <td>{{ item.count }}</td>
                    <td>{{ item.unit }}</td>
                    <td>
                      <span v-if="item.acc_mark !== 0" class="modification-count">
                        {{ getModificationCount(item.id, 'jx') }}次
                      </span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 仪表使用费 -->
          <view v-if="currentDetailTab === 3" class="detail-section">
            <view class="highlight-tip">绿色高亮的行表示根据验收情况修改过。高亮深度表示修改次数，单击可跳转对应的记录</view>
            <view v-if="detailData.instrumentFees.length === 0" class="empty-message">
              暂无仪表使用费数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>定额编码</th>
                    <th>定额名称</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th>修改次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.instrumentFees" :key="idx" 
                    :class="getHighlightClass(item.acc_mark, getModificationCount(item.id, 'yb'))"
                    @click="item.acc_mark !== 0 && navigateToHistory(item.id, 'yb')">
                    <td>{{ idx + 1 }}</td>
                    <td>
                      <a 
                        href="javascript:void(0)" 
                        @click.stop="previewDeFile(item.de_id)"
                        class="de-code-link"
                      >
                        {{ item.de_id }}
                      </a>
                    </td>
                    <td>{{ item.de_name }}</td>
                    <td>{{ item.count }}</td>
                    <td>{{ item.unit }}</td>
                    <td>
                      <span v-if="item.acc_mark !== 0" class="modification-count">
                        {{ getModificationCount(item.id, 'yb') }}次
                      </span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 甲供材料 -->
          <view v-if="currentDetailTab === 4" class="detail-section">
            <view class="highlight-tip">绿色高亮的行表示根据验收情况修改过。高亮深度表示修改次数，单击可跳转对应的记录</view>
            <view v-if="detailData.supplierAMaterials.length === 0" class="empty-message">
              暂无甲供材料数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>材料名称</th>
                    <th>规格型号</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th>修改次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.supplierAMaterials" :key="idx" 
                    :class="getHighlightClass(item.acc_mark, getModificationCount(item.id, 'jg'))"
                    @click="item.acc_mark !== 0 && navigateToHistory(item.id, 'jg')">
                    <td>{{ item.id }}</td>
                    <td>{{ item.mat_name }}</td>
                    <td>{{ item.mat_type }}</td>
                    <td>{{ item.mat_count }}</td>
                    <td>{{ item.mat_unit }}</td>
                    <td>
                      <span v-if="item.acc_mark !== 0" class="modification-count">
                        {{ getModificationCount(item.id, 'jg') }}次
                      </span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 乙供材料 -->
          <view v-if="currentDetailTab === 5" class="detail-section">
            <view class="highlight-tip">绿色高亮的行表示根据验收情况修改过。高亮深度表示修改次数，单击可跳转对应的记录</view>
            <view v-if="detailData.supplierBMaterials.length === 0" class="empty-message">
              暂无乙供材料数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>材料名称</th>
                    <th>规格型号</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th>修改次数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.supplierBMaterials" :key="idx" 
                    :class="getHighlightClass(item.acc_mark, getModificationCount(item.id, 'yg'))"
                    @click="item.acc_mark !== 0 && navigateToHistory(item.id, 'yg')">
                    <td>{{ item.id }}</td>
                    <td>{{ item.mat_name }}</td>
                    <td>{{ item.mat_type }}</td>
                    <td>{{ item.mat_count }}</td>
                    <td>{{ item.mat_unit }}</td>
                    <td>
                      <span v-if="item.acc_mark !== 0" class="modification-count">
                        {{ getModificationCount(item.id, 'yg') }}次
                      </span>
                      <span v-else>-</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 其他费用 -->
          <view v-if="currentDetailTab === 6" class="detail-section">
            <view v-if="detailData.otherFees.length === 0" class="empty-message">
              暂无其他费用数据
            </view>
            <view v-else class="detail-table-wrapper">
              <table class="detail-table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>费用名称</th>
                    <th>计算依据及方法</th>
                    <th>除税价（元）</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, idx) in detailData.otherFees" :key="idx">
                    <td>{{ idx + 1 }}</td>
                    <td>{{ item.cost_name }}</td>
                    <td>{{ item.cost_desc }}</td>
                    <td>{{ item.cost_price }}</td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>

          <!-- 历史验收情况 -->
          <view v-if="currentDetailTab === 7" class="detail-section">
            <view v-if="detailData.historyProblems.length === 0" class="empty-message">
              暂无历史验收记录
            </view>
            <view v-else>
              <view
                v-for="(group, index) in groupedDetailProblems"
                :key="index"
                class="history-group"
              >
                <text class="history-header">第{{ group.type }}次验收</text>
                <view class="detail-table-wrapper">
                  <table class="detail-table">
                    <thead>
                      <tr>
                        <th>序号</th>
                        <th>验收人</th>
                        <th>验收日期</th>
                        <th>验收项目</th>
                        <th>原始值</th>
                        <th>修正值</th>
                        <th>类型</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(item, idx) in group.items" :key="idx">
                        <td>{{ item.id }}</td>
                        <td>{{ item.accPerson }}</td>
                        <td>{{ formatDate(item.accDate) }}</td>
                        <td>{{ item.accName }}</td>
                        <td>{{ item.wrongValue }}</td>
                        <td>{{ item.rightValue }}</td>
                        <td>{{ getTypeText(item.type) }}</td>
                        <td>
                          <div class="button-container">
                            <button class="location-btn" @click="showLocation(item)">查看位置</button>
                            <button class="location-btn" @click="showImage(item)">查看图片</button>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 位置查看模态框 -->
          <uni-popup ref="location_modal" type="center">
            <view class="location-modal">
              <view class="location-modal-header">
                <text class="location-modal-title">验收位置</text>
                <button class="close-btn" @click="closeLocationModal">×</button>
              </view>
              <map
                v-if="currentLocation"
                :latitude="currentLocation.lat"
                :longitude="currentLocation.lng"
                :markers="[{
                  id: 1,
                  latitude: currentLocation.lat,
                  longitude: currentLocation.lng,
                  width: 30,
                  height: 30,
                  iconPath: '/static/location.png',
                }]"
                style="width: 100%; height: 300px;"
              ></map>
            </view>
          </uni-popup>
          
<!-- 图片查看模态框 -->
          <uni-popup ref="image_modal" type="center">
            <view class="image-modal">
              <view class="image-modal-header">
                <text class="image-modal-title">验收图片</text>
                <button class="close-btn" @click="closeImageModal">×</button>
              </view>
              <view class="image-container">
                <swiper 
                  v-if="imageList.length > 0" 
                  class="image-swiper" 
                  :indicator-dots="imageList.length > 1"
                  indicator-color="rgba(0, 0, 0, .3)"
                  indicator-active-color="#409eff"
                >
                  <swiper-item v-for="(img, index) in imageList" :key="index">
                    <image 
                      :src="img" 
                      mode="aspectFit"
                      style="width: 100%; max-height: 400px;"
                    ></image>
                  </swiper-item>
                </swiper>
                <view v-else class="empty-message">暂无图片</view>
              </view>
            </view>
          </uni-popup>
        </view>
      </view>
    </uni-popup>

    <!-- 表格主体，撑满剩余高度可滚动 -->
    <view class="table-wrapper">
      <table class="data-table" v-if="!return_proj_list && role == 'rose2'">
        <thead>
          <tr>
            <th style="width: 3%">ID</th>
            <th style="width: 13%">项目MIS编码</th>
            <th style="width: 13%">项目名称</th>
            <th style="width: 13%">子任务ID</th>
            <th style="width: 13%">站点名称</th>
            <th style="width: 10">区县公司</th>
            <th style="width: 7%">项目经理</th>
            <th style="width: 7%" @click="toggleSort">
              造价（元）
              <text v-if="sortPriceAsc === true">↑</text>
              <text v-else-if="sortPriceAsc === false">↓</text>
            </th>
            <th style="width: 11%">项目文件</th>
            <th style="width: 7%">是否验收</th>
            <th style="width: 5%">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="paginatedData.length === 0">
            <td colspan="18" class="empty-row">暂无数据</td>
          </tr>
          <tr
            v-for="(item, index) in paginatedData"
            :key="item.id || index"
            class="data-row"
            @click="handleRowClick(item)"
          >
            <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
            <td>{{ item.misCode }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.subtaskId }}</td>
            <td>{{ item.siteName }}</td>

            <td>{{ item.company }}</td>
            <td class="manager-cell">{{ item.manager }}</td>
            <td>{{ item.cost }}</td>
            <td>
              <view class="button-container">
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'xlsx')"
                >
                  结算表
                </button>
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'pdf')"
                >
                  图纸
                </button>
              </view>
            </td>
            <td>{{ item.isacc == "false" ? "否" : "是" }}</td>
            <td>
              <button class="delete-btn" @click.stop="deleteItem(item)">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <table class="data-table" v-else-if="return_proj_list && role == 'rose2'">
        <thead>
          <tr>
            <th style="width: 3%">ID</th>
            <th style="width: 12%">项目MIS编码</th>
            <th style="width: 12%">项目名称</th>
            <th style="width: 12%">子任务ID</th>
            <th style="width: 12%">站点名称</th>
            <th style="width: 7%">区县公司</th>
            <th style="width: 7%">项目经理</th>
            <th style="width: 10%" @click="toggleSort">
              造价（元）
              <text v-if="sortPriceAsc === true">↑</text>
              <text v-else-if="sortPriceAsc === false">↓</text>
            </th>
            <th style="width: 10%">项目文件</th>
            <th style="width: 10%">工单历时（h）</th>
            <th style="width: 15%">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="paginatedData.length === 0">
            <td colspan="18" class="empty-row">暂无数据</td>
          </tr>
          <tr
            v-for="(item, index) in paginatedData"
            :key="item.id || index"
            class="data-row"
            @click="handleRowClick(item)"
          >
            <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
            <td>{{ item.misCode }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.subtaskId }}</td>
            <td>{{ item.siteName }}</td>

            <td>{{ item.company }}</td>
            <td>{{ item.manager }}</td>
            <td>{{ item.cost }}</td>
            <td>
              <view class="button-container">
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'xlsx')"
                >
                  结算表
                </button>
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'pdf')"
                >
                  图纸
                </button>
              </view>
            </td>
            <td>{{ item.order_time }}</td>
            <td>
              <button class="delete-btn" @click.stop="show_approve_modal(item)">
                处理
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <table
        class="data-table"
        v-else-if="!return_proj_list && role == 'rose3'"
      >
        <thead>
          <tr>
            <th style="width: 3%">ID</th>
            <th style="width: 12%">项目MIS编码</th>
            <th style="width: 12%">项目名称</th>
            <th style="width: 12%">子任务ID</th>
            <th style="width: 12%">站点名称</th>
            <th style="width: 7%">区县公司</th>
            <th style="width: 7%">项目经理</th>
            <th style="width: 10%" @click="toggleSort">
              造价（元）
              <text v-if="sortPriceAsc === true">↑</text>
              <text v-else-if="sortPriceAsc === false">↓</text>
            </th>
            <th style="width: 10%">项目文件</th>
            <th style="width: 7%">是否验收</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="paginatedData.length === 0">
            <td colspan="18" class="empty-row">暂无数据</td>
          </tr>
          <tr
            v-for="(item, index) in paginatedData"
            :key="item.id || index"
            class="data-row"
            @click="handleRowClick(item)"
          >
            <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
            <td>{{ item.misCode }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.subtaskId }}</td>
            <td>{{ item.siteName }}</td>

            <td>{{ item.company }}</td>
            <td>{{ item.manager }}</td>
            <td>{{ item.cost }}</td>
            <td>
              <view class="button-container">
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'xlsx')"
                >
                  结算表
                </button>
                <button
                  class="preview-btn"
                  @click.stop="previewFile(item, 'pdf')"
                >
                  图纸
                </button>
              </view>
            </td>
            <td>{{ item.isacc === "false" ? "否" : "是" }}</td>
          </tr>
        </tbody>
      </table>
      <table class="data-table" v-else-if="return_proj_list && role == 'rose3'">
        <thead>
          <tr>
            <th style="width: 3%">ID</th>
            <th style="width: 12%">项目MIS编码</th>
            <th style="width: 12%">项目名称</th>
            <th style="width: 12%">子任务ID</th>
            <th style="width: 12%">站点名称</th>
            <th style="width: 7%">审批人</th>
            <th style="width: 7%">审批状态</th>
            <th style="width: 7%">审批结果</th>
            <th style="width: 15%">审批意见</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="paginatedData.length === 0">
            <td colspan="18" class="empty-row">暂无数据</td>
          </tr>
          <tr
            v-for="(item, index) in paginatedData"
            :key="item.id || index"
            class="data-row"
            @click="handleRowClick(item)"
          >
            <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
            <td>{{ item.misCode }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.subtaskId }}</td>
            <td>{{ item.siteName }}</td>
            <td>{{ item.approve_person }}</td>
            <td>{{ item.is_approve === "true" ? "已审批" : "未审批" }}</td>
            <td>{{ item.approve_result === "yes" ? "通过" : item.approve_result === "no" ? "驳回" : "" }}</td>
            <td>{{ item.approve_tip }}</td>
          </tr>
        </tbody>
      </table>
    </view>

    <!-- 分页控件 -->
    <view class="pagination">
      <button
        class="page-btn"
        :disabled="currentPage === 1"
        @click="setPage(currentPage - 1)"
      >
        上一页
      </button>
      <text class="page-info">
        第 {{ currentPage }} / {{ totalPages }} 页
      </text>
      <button
        class="page-btn"
        :disabled="currentPage === totalPages"
        @click="setPage(currentPage + 1)"
      >
        下一页
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, defineExpose, nextTick } from "vue";

const role = ref(uni.getStorageSync("userInfo").role);

const dataList = ref([]);
const isLoading = ref(false);
const deleteError = ref("");
// 新增：审批工单相关数据
const approvalList = ref([]);
const approvalCount = ref(0);
const isApprovalMode = ref(false);
const approve_view = ref(false);
const approve_modal = ref(null);
const currentApprovalItem = ref(null);
const approveOpinion = ref("");
const return_proj_list = ref(false);

const companyOptions = ref(["全部"]);
const selectedCompanyIndex = ref(0);
const filterCompany = computed(() => {
  return selectedCompanyIndex.value === 0
    ? ""
    : companyOptions.value[selectedCompanyIndex.value];
});

// 搜索相关
const searchKeyword = ref("");

// 搜索输入处理
const onSearchInput = () => {
  currentPage.value = 1; // 搜索时重置到第一页
};

// 排序状态
const sortPriceAsc = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 获取token函数（实际项目中可能从storage获取）
const getToken = () => {
  // 示例：从本地存储获取token
  return uni.getStorageSync("userInfo").token;
};

// 后端接口：获取项目数据
const fetchData = () => {
  isLoading.value = true;
  uni.request({
    url: "./api/projects",
    method: "GET",
    header: {
      Authorization: `Bearer ${getToken()}`, // 添加token
    },
    success: (res) => {
      if (Array.isArray(res.data)) {
        dataList.value = res.data;

        // 构建区县公司选项：去重并排序
        const companySet = new Set();
        res.data.forEach((item) => {
          if (item.company) {
            companySet.add(item.company);
          }
        });
        const sortedCompanies = Array.from(companySet).sort();
        companyOptions.value = ["全部", ...sortedCompanies];
      } else {
        dataList.value = [];
        companyOptions.value = ["全部"];
      }
    },
    fail: (err) => {
      console.error("fetchData 错误：", err);
      dataList.value = [];
      companyOptions.value = ["全部"];
    },
    complete: () => {
      isLoading.value = false;
    },
  });
};

// 新增：获取审批工单数量
const fetchApprovalCount = () => {
  uni.request({
    url: "./api/approv",
    method: "GET",
    data: {
      type: "count",
    },
    header: {
      Authorization: `Bearer ${getToken()}`, // 添加token
    },
    success: (res) => {
      if (res.data && typeof res.data.count === "number") {
        approvalCount.value = res.data.count;
      }
    },
    fail: (err) => {
      console.error("fetchApprovalCount 错误：", err);
    },
  });
};

// 新增：获取审批工单数据
const fetchApprovalData = () => {
  return_proj_list.value = true;
  approve_view.value = true;
  isLoading.value = true;
  isApprovalMode.value = true;
  uni.request({
    url: "./api/approv",
    method: "GET",
    data: {
      type: "data",
    },
    header: {
      Authorization: `Bearer ${getToken()}`, // 添加token
    },
    success: (res) => {
      if (Array.isArray(res.data)) {
        approvalList.value = res.data;
        // 重置分页
        currentPage.value = 1;
      } else {
        approvalList.value = [];
      }
    },
    fail: (err) => {
      console.error("fetchApprovalData 错误：", err);
      approvalList.value = [];
    },
    complete: () => {
      isLoading.value = false;
    },
  });
};

// 计算：根据当前模式选择数据源
const currentData = computed(() => {
  return isApprovalMode.value ? approvalList.value : dataList.value;
});

// 计算：先搜索，再筛选，再排序，再分页
const filteredData = computed(() => {
  let data = currentData.value.slice();
  
  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase();
    data = data.filter((item) => {
      return (
        (item.projectName && item.projectName.toLowerCase().includes(keyword)) ||
        (item.misCode && item.misCode.toLowerCase().includes(keyword)) ||
        (item.siteName && item.siteName.toLowerCase().includes(keyword)) ||
        (item.subtaskId && item.subtaskId.toLowerCase().includes(keyword)) ||
        (item.manager && item.manager.toLowerCase().includes(keyword))
      );
    });
  }
  
  // 区县公司筛选
  if (filterCompany.value && !isApprovalMode.value) {
    data = data.filter((item) => item.company === filterCompany.value);
  }
  
  return data;
});

const sortedData = computed(() => {
  const list = filteredData.value.slice();
  if (sortPriceAsc.value === null) {
    return list;
  }
  return list.sort((a, b) => {
    const aCost = parseFloat(a.cost) || 0;
    const bCost = parseFloat(b.cost) || 0;
    if (sortPriceAsc.value) {
      return aCost - bCost;
    } else {
      return bCost - aCost;
    }
  });
});

const totalPages = computed(() => {
  return Math.max(1, Math.ceil(sortedData.value.length / pageSize.value));
});
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return sortedData.value.slice(start, start + pageSize.value);
});

// 切换排序状态
const toggleSort = () => {
  if (sortPriceAsc.value === null) {
    sortPriceAsc.value = true;
  } else if (sortPriceAsc.value === true) {
    sortPriceAsc.value = false;
  } else {
    sortPriceAsc.value = null;
  }
  currentPage.value = 1;
};

// 筛选条件变化
const onFilterChange = (event) => {
  selectedCompanyIndex.value = event.detail.value;
  currentPage.value = 1;
};

// 切换分页
const setPage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

// 详情模态框相关数据
const detail_modal = ref(null);
const location_modal = ref(null);
const image_modal = ref(null);
const currentLocation = ref(null);
const imageList = ref([]);
const currentDetailTab = ref(0);
const detailTabs = ref([
  { title: "定额不一致", key: "overLimits" },
  { title: "用量清单", key: "usageList" },
  { title: "机械使用费", key: "machineryFees" },
  { title: "仪表使用费", key: "instrumentFees" },
  { title: "甲供材料", key: "supplierAMaterials" },
  { title: "乙供材料", key: "supplierBMaterials" },
  { title: "其他费用", key: "otherFees" },
  { title: "历史验收情况", key: "historyProblems" },
]);

const detailData = ref({
  overList: [],
  usageList: [],
  machineryFees: [],
  instrumentFees: [],
  supplierAMaterials: [],
  supplierBMaterials: [],
  otherFees: [],
  historyProblems: []
});

// 历史问题分组计算属性
const groupedDetailProblems = computed(() => {
  const groups = {};
  
  if (Array.isArray(detailData.value.historyProblems)) {
    detailData.value.historyProblems.forEach((item) => {
      const acceptanceNumber = item.acceptanceNumber || 1;
      if (!groups[acceptanceNumber]) {
        groups[acceptanceNumber] = { type: acceptanceNumber, items: [] };
      }
      groups[acceptanceNumber].items.push(item);
    });
  }
  
  return Object.values(groups).sort((a, b) => a.type - b.type);
});

// 组件通信 - 修改为打开模态框
const handleRowClick = (item) => {
  // 打开详情模态框
  openDetailModal(item);
};

// 打开详情模态框
const openDetailModal = (item) => {
  currentDetailTab.value = 0;
  loadDetailData(item.misCode, item.subtaskId);
  detail_modal.value.open();
};

// 关闭详情模态框
const closeDetailModal = () => {
  detail_modal.value.close();
};

// 显示位置模态框
const showLocation = (item) => {
  currentLocation.value = {
    lat: parseFloat(item.lat),
    lng: parseFloat(item.lng)
  };
  location_modal.value.open();
};

// 关闭位置模态框
const closeLocationModal = () => {
  location_modal.value.close();
};

// 显示图片模态框
const showImage = (item) => {
  // 如果有图片路径，则显示图片
  if (item.imagePath) {
    // 图片路径可能是多个URL以逗号分隔
    const urls = item.imagePath.split(',').filter(url => url.trim() !== '');
    
    if (urls.length > 0) {
      // 清空之前的图片列表
      imageList.value = [];
      
      // 直接使用后端提供的URL
      urls.forEach(url => {
        imageList.value.push(url);
      });
      
      image_modal.value.open();
    } else {
      uni.showToast({
        title: "图片路径无效",
        icon: "none"
      });
    }
  } else {
    uni.showToast({
      title: "暂无图片",
      icon: "none"
    });
  }
};

// 关闭图片模态框
const closeImageModal = () => {
  image_modal.value.close();
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(parseInt(timestamp) * 1000);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    'jg': '甲供材料',
    'yg': '乙供材料',
    'usage': '用量清单',
    'jx': '机械使用费',
    'yb': '仪表使用费'
  };
  return typeMap[type] || type;
};

// 切换详情选项卡
const switchDetailTab = (index) => {
  currentDetailTab.value = index;
};

// 获取修改次数
const getModificationCount = (itemId, itemType) => {
  if (!detailData.value.historyProblems || detailData.value.historyProblems.length === 0) {
    return 0;
  }
  
  return detailData.value.historyProblems.filter(problem => 
    problem.accNameId == itemId && problem.type === itemType
  ).length;
};

// 根据修改次数获取高亮样式类
const getHighlightClass = (accMark, modificationCount) => {
  if (accMark === 0 || modificationCount === 0) {
    return '';
  }
  
  if (modificationCount === 1) {
    return 'highlighted-row-light';
  } else if (modificationCount === 2) {
    return 'highlighted-row-medium';
  } else {
    return 'highlighted-row-heavy';
  }
};

// 导航到历史验收情况并高亮对应记录
const navigateToHistory = (id, itemType) => {
  // 切换到历史验收情况选项卡
  currentDetailTab.value = 7;
  
  // 使用nextTick确保DOM更新后再执行高亮操作
  nextTick(() => {
    // 先移除所有之前的高亮
    const allHistoryRecords = document.querySelectorAll('.detail-table tbody tr');
    allHistoryRecords.forEach(record => {
      record.classList.remove('current-highlight');
    });
    
    // 找到所有匹配的记录
    let matchedElements = [];
    
    // 查找匹配的历史记录并高亮
    const historyRecords = document.querySelectorAll('.detail-table tbody tr');
    historyRecords.forEach(record => {
      // 获取当前行的数据
      const cells = record.querySelectorAll('td');
      if (cells.length >= 8) { // 确保有足够的列
        const recordId = cells[0].textContent.trim();
        const recordType = cells[7].textContent.trim(); // 类型列
        
        // 根据ID和类型进行匹配
        const matchingProblems = detailData.value.historyProblems.filter(problem => 
          problem.accNameId == id && problem.type === itemType
        );
        
        // 检查当前行是否匹配任何一个问题记录
        const isMatched = matchingProblems.some(problem => problem.id == recordId);
        
        if (isMatched) {
          record.classList.add('current-highlight');
          matchedElements.push(record);
        }
      }
    });
    
    // 滚动到第一个匹配的元素
    if (matchedElements.length > 0) {
      matchedElements[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
      
      // 显示匹配数量提示
      uni.showToast({
        title: `找到 ${matchedElements.length} 条相关记录`,
        icon: 'none',
        duration: 2000
      });
    } else {
      uni.showToast({
        title: '未找到相关历史记录',
        icon: 'none',
        duration: 2000
      });
    }
  });
};

// 加载详情数据
const loadDetailData = (misId, taskId) => {
  // 重置数据
  detailData.value = {
    overList: [],
    usageList: [],
    machineryFees: [],
    instrumentFees: [],
    supplierAMaterials: [],
    supplierBMaterials: [],
    otherFees: [],
    historyProblems: []
  };

  // 加载所有数据
  loadOverLimitsData(misId, taskId);
  loadUsageListData(misId, taskId);
  loadMachineryFeesData(misId, taskId);
  loadInstrumentFeesData(misId, taskId);
  loadSupplierAMaterials(misId, taskId);
  loadSupplierBMaterials(misId, taskId);
  loadOtherFeesData(misId, taskId);
  loadHistoryProblems(misId, taskId);
};

// 数据加载函数
const loadOverLimitsData = (misId, taskId) => {
  uni.request({
    url: `./api/overLimits?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.overList = res.data;
      }
    },
    fail: (err) => console.error("获取定额不一致数据失败：", err)
  });
};

const loadUsageListData = (misId, taskId) => {
  uni.request({
    url: `./api/usageList?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.usageList = res.data;
      }
    },
    fail: (err) => console.error("获取用量清单数据失败：", err)
  });
};

const loadMachineryFeesData = (misId, taskId) => {
  uni.request({
    url: `./api/table3y?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.machineryFees = res.data;
      }
    },
    fail: (err) => console.error("获取机械使用费数据失败：", err)
  });
};

const loadInstrumentFeesData = (misId, taskId) => {
  uni.request({
    url: `./api/table3b?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.instrumentFees = res.data;
      }
    },
    fail: (err) => console.error("获取仪表使用费数据失败：", err)
  });
};

const loadSupplierAMaterials = (misId, taskId) => {
  uni.request({
    url: `./api/jgmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.supplierAMaterials = res.data;
      }
    },
    fail: (err) => console.error("获取甲供材料数据失败：", err)
  });
};

const loadSupplierBMaterials = (misId, taskId) => {
  uni.request({
    url: `./api/ygmat?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.supplierBMaterials = res.data;
      }
    },
    fail: (err) => console.error("获取乙供材料数据失败：", err)
  });
};

const loadOtherFeesData = (misId, taskId) => {
  uni.request({
    url: `./api/table5?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        detailData.value.otherFees = res.data;
      }
    },
    fail: (err) => console.error("获取其他费用数据失败：", err)
  });
};

const loadHistoryProblems = (misId, taskId) => {
  uni.request({
    url: `./api/historyProblems?misId=${misId}&taskId=${taskId}`,
    method: "GET",
    header: { Authorization: `Bearer ${getToken()}` },
    success: (res) => {
      if (res.statusCode === 200) {
        // 处理返回的数据结构
        const historyData = res.data;
        const processedData = [];
        
        // 遍历每个验收次数
        for (const acceptanceNumber in historyData) {
          if (historyData.hasOwnProperty(acceptanceNumber)) {
            const acceptanceRecords = historyData[acceptanceNumber];
            
            // 处理每个验收记录
            if (Array.isArray(acceptanceRecords) && acceptanceRecords.length > 0) {
              acceptanceRecords.forEach(item => {
                if (Array.isArray(item) && item.length >= 10) {
                  processedData.push({
                    id: item[0],
                    accDate: item[1],
                    accPerson: item[2],
                    accName: item[3], // 暂时保留ID
                    accNameId: item[3], // 保存原始ID用于查询
                    wrongValue: item[4],
                    rightValue: item[5],
                    imagePath: item[6], // 这里是直接可用的URL，可能包含多个URL以逗号分隔
                    type: item[7],
                    lat: item[8],
                    lng: item[9],
                    acceptanceNumber: parseInt(acceptanceNumber)
                  });
                }
              });
            }
          }
        }
        
        // 设置处理好的数据
        detailData.value.historyProblems = processedData;
        
        // 使用已加载的数据替换名称
        updateHistoryProblemNames();
      }
    },
    fail: (err) => console.error("获取历史验收数据失败：", err)
  });
};

// 从已加载的数据中查找并更新历史验收项目的名称
const updateHistoryProblemNames = () => {
  if (!detailData.value.historyProblems || detailData.value.historyProblems.length === 0) {
    return;
  }
  
  // 遍历所有历史验收记录
  detailData.value.historyProblems.forEach((item, index) => {
    const itemType = item.type;
    const itemId = item.accNameId;
    let matchedName = null;
    
    // 根据类型从对应的已加载数据中查找匹配项
    switch(itemType) {
      case 'usage':
        // 从用量清单中查找
        const usageItem = detailData.value.usageList.find(dataItem => dataItem.id == itemId);
        if (usageItem) {
          matchedName = usageItem.de_name;
        }
        break;
      case 'jx':
        // 从机械使用费中查找
        const machineryItem = detailData.value.machineryFees.find(dataItem => dataItem.id == itemId);
        if (machineryItem) {
          matchedName = machineryItem.de_name;
        }
        break;
      case 'yb':
        // 从仪表使用费中查找
        const instrumentItem = detailData.value.instrumentFees.find(dataItem => dataItem.id == itemId);
        if (instrumentItem) {
          matchedName = instrumentItem.de_name;
        }
        break;
      case 'jg':
        // 从甲供材料中查找
        const supplierAItem = detailData.value.supplierAMaterials.find(dataItem => dataItem.id == itemId);
        if (supplierAItem) {
          matchedName = supplierAItem.mat_name;
        }
        break;
      case 'yg':
        // 从乙供材料中查找
        const supplierBItem = detailData.value.supplierBMaterials.find(dataItem => dataItem.id == itemId);
        if (supplierBItem) {
          matchedName = supplierBItem.mat_name;
        }
        break;
    }
    
    // 如果找到匹配的名称，则更新
    if (matchedName) {
      detailData.value.historyProblems[index].accName = matchedName;
    }
  });
};

// 删除项目
const deleteItem = (item) => {
  uni.showModal({
    title: "确认删除",
    content: `确定要删除项目 ${item.misCode} 吗？`,
    success: (res) => {
      if (res.confirm) {
        deleteError.value = "";
        uni.request({
          url: `./api/dd?misId=${item.misCode}&taskId=${item.subtaskId}`,
          method: "DELETE",
          header: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${getToken()}`, // 添加token
          },
          success: (res) => {
            if (res.statusCode === 200) {
              uni.showToast({
                title: "删除成功",
                icon: "success",
              });
              // 重新获取最新数据
              if (isApprovalMode.value) {
                fetchApprovalData();
              } else {
                fetchData();
              }
              // 重置页码为第一页
              currentPage.value = 1;
              
              // 问题2：删除后同步刷新数据看板
              // 通过事件通知父组件刷新看板数据
              uni.$emit('refreshDashboard');
            } else {
              deleteError.value = res.data.message || "删除失败，请重试";
              uni.showToast({
                title: deleteError.value,
                icon: "none",
              });
            }
          },
          fail: (err) => {
            deleteError.value = "网络错误，请重试";
            console.error("删除失败：", err);
            uni.showToast({
              title: "删除失败，请重试",
              icon: "none",
            });
          },
        });
      }
    },
  });
};

// 处理审批
const show_approve_modal = (item) => {
  currentApprovalItem.value = item; // 保存当前审批项
  approveOpinion.value = ""; // 清空上次输入
  approve_modal.value.open();
};

const closeModal = () => {
  approve_modal.value.close();
};

// 审批通过
const approve_accept = () => {
  handleApproval("yes");
};

// 审批驳回
const approve_resuse = () => {
  handleApproval("no");
};

// 通用审批处理函数
const handleApproval = (result) => {
  if (!currentApprovalItem.value) {
    uni.showToast({ title: "未获取到审批项", icon: "none" });
    return;
  }

  if (!approveOpinion.value.trim()) {
    uni.showToast({ title: "请输入审批意见", icon: "none" });
    return;
  }

  uni.request({
    url: "./api/appres",
    method: "POST",
    header: {
      Authorization: `Bearer ${getToken()}`,
      "Content-Type": "application/json",
    },
    data: {
      misId: currentApprovalItem.value.misCode, // 项目MIS编码
      taskId: currentApprovalItem.value.subtaskId, // 子任务ID
      opinion: approveOpinion.value.trim(), // 审批意见
      result: result, // 审批结果（yes/no）
    },
    success: (res) => {
      if (res.statusCode === 200) {
        uni.showToast({ title: "审批操作成功", icon: "success" });
        // 刷新审批列表数据
        fetchApprovalData();
        // 关闭模态框
        closeModal();
        
        // 审批处理后也要刷新数据看板
        uni.$emit('refreshDashboard');
      } else {
        uni.showToast({ title: res.data.message || "审批失败", icon: "none" });
      }
    },
    fail: (err) => {
      console.error("审批请求失败：", err);
      uni.showToast({ title: "网络错误，请重试", icon: "none" });
    },
  });
};

// 预览定额文件 - H5环境
const previewDeFile = (deCode) => {
  if (!deCode) {
    uni.showToast({ title: "定额编码不能为空", icon: "none" });
    return;
  }

  uni.showLoading({ title: "文件加载中...", mask: true });
  
  // H5环境：使用fetch获取PDF文件并在新窗口打开
  const pdfUrl = `./api/searchDeFile?deFile=${encodeURIComponent(deCode)}`;
  const token = getToken();
  
  fetch(pdfUrl, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`
    }
  }).then(response => {
    if (response.ok) {
      return response.blob();
    } else {
      return response.text().then(text => {
        let errorMessage = "文件未找到";
        try {
          const errorData = JSON.parse(text);
          errorMessage = errorData.message || errorMessage;
        } catch (e) {
          // 如果不是JSON格式，使用默认错误信息
        }
        throw new Error(errorMessage);
      });
    }
  }).then(blob => {
    // 创建blob URL并在新窗口打开
    const url = window.URL.createObjectURL(blob);
    const newWindow = window.open(url, '_blank');
    
    if (!newWindow) {
      // 如果弹窗被阻止，提供下载链接
      const link = document.createElement('a');
      link.href = url;
      link.download = `定额文件_${deCode}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      uni.showToast({
        title: "文件已下载",
        icon: "success",
      });
    }
    
    // 延迟释放URL对象
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
    }, 1000);
    
  }).catch(error => {
    console.error("预览定额文件失败", error);
    uni.showToast({
      title: error.message || "文件预览失败，请重试",
      icon: "none",
    });
  }).finally(() => {
    uni.hideLoading();
  });
};
const fetchTableData = () => {
  return_proj_list.value = false;
  approve_view.value = false;
  isLoading.value = false;
  isApprovalMode.value = false;
  fetchData();
  fetchApprovalCount();
};

const previewFile = (item, fileType) => {
  const apiUrl =
    fileType === "xlsx"
      ? `./api/preview/${item.uuid}/${item.file_xlsx}`
      : `./api/preview/${item.uuid}/${item.file_pdf}`;

  uni.showLoading({ title: "文件加载中...", mask: true });
  uni.downloadFile({
    url: apiUrl,
    header: {
      Authorization: `Bearer ${getToken()}`,
    },
    success: (res) => {
      if (res.statusCode === 200) {
        uni.openDocument({
          filePath: res.tempFilePath,
          success: () => {
            // console.log("文件打开成功");
          },
          fail: (err) => {
            console.error("文件打开失败", err);
            uni.showToast({
              title: "文件预览失败，请重试",
              icon: "none",
            });
          },
        });
      } else {
        console.error(
          "下载文件失败，状态码:",
          res.statusCode,
          "响应数据:",
          res.data
        );
        uni.showToast({
          title: "文件下载失败，请重试",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      console.error("下载请求失败", err);
      uni.showToast({
        title: "网络请求失败，请检查网络",
        icon: "none",
      });
    },
    complete: () => {
      // 无论成功/失败都关闭加载提示
      uni.hideLoading();
    },
  });
};

// 生命周期：加载数据
onMounted(() => {
  fetchData();
  fetchApprovalCount(); // 新增：获取审批工单数量
});

defineExpose({
  fetchData,
});
</script>

<style scoped>
/* 保持原有样式不变 */
.table-card {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.table-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333333;
}

/* 搜索框样式 */
.search-container {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
  height: 36px;
  padding: 8px 40px 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  transition: border-color 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #409eff;
}

.search-input::placeholder {
  color: #c0c4cc;
}

.search-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #c0c4cc;
  font-size: 16px;
  pointer-events: none;
}

.filter-group {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 8px;
  font-size: 0.95rem;
  color: #555555;
}

.filter-picker {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 0.95rem;
  width: 120px;
  text-align: center;
}

.picker-display {
  line-height: 32px;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
  margin-top: 12px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.95rem;
}

.data-table thead th {
  background-color: #f5f7fa;
  color: #333333;
  font-weight: 600;
  padding: 12px 8px;
  border-bottom: 2px solid #e0e0e0;
  text-align: center;
  position: sticky;
  top: 0;
  z-index: 1;
  cursor: pointer;
}

.data-table tbody td {
  padding: 12px 8px;
  border-bottom: 1px solid #eaeaea;
  text-align: center;
}

.empty-row {
  text-align: center;
  color: #999999;
  padding: 20px 0;
}

.data-row:nth-child(odd) {
  background-color: #fafafa;
}

.data-row:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 12px;
}

.page-btn {
  background-color: #409eff;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 0.95rem;
  margin: 0 8px;
}

.page-btn:disabled {
  background-color: #a0cfff;
  color: #ffffff;
}

.page-info {
  font-size: 0.95rem;
  color: #555555;
}

.delete-btn {
  background-color: #f56c6c;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  padding: 2px 4px;
  font-size: 0.9rem;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: #f78989;
}

/* 新增：审批工单按钮样式 */
.approval-btn {
  background-color: #127ae2be;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  font-size: 0.95rem;
  margin-left: 10px;
  position: relative;
  /* height: 40px; */
}

.approval-btn:hover {
  background-color: #409eff;
}

.badge {
  position: absolute;
  top: 0px;
  right: 0px;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}

.modal-content {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
  text-align: center;
}

.btn-group {
  display: flex;
  justify-content: flex-end;
}

.modal-close {
  margin-top: 30rpx;
  background: #127ae2be;
  color: white;
  border-radius: 8rpx;
  height: 35px;
  font-size: 1rem;
}

.approve-input {
  height: 100px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  font-size: 14px;
  width: 94%;
  /* 新增样式 */
  text-align: left;
  /* 占位符和输入内容居中 */
  vertical-align: top;
  /* 内容从顶部开始显示 */
  white-space: pre-wrap;
  /* 自动换行 */
  word-wrap: break-word;
  /* 长单词/URL强制换行 */
  resize: none;
  /* 禁止用户调整文本域大小（可选） */
}

.button-container {
  display: flex;
  flex-direction: row; /* 让按钮水平排列 */
  gap: 8px; /* 设置按钮之间的间距 */
  justify-content: center; /* 水平居中按钮 */
  align-items: center; /* 垂直居中按钮 */
}

.preview-btn {
  background-color: #409eff;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  padding: 4px 8px; /* 调整按钮内边距 */
  white-space: nowrap; /* 防止按钮文字换行 */
}

.preview-btn:hover {
  background-color: #66b1ff;
}

/* 详情模态框样式 */
.detail-modal-content {
  background: white;
  border-radius: 12px;
  width: 90vw;
  max-width: 1000px;
  height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-modal-header {
  position: relative;
  padding: 20px 24px;
  border-bottom: 1px solid #e0e0e0;
}

.detail-modal-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 20px;
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.close-btn:hover {
  background-color: #f5f5f5;
}

.detail-tab-nav {
  display: flex;
  padding: 0 24px;
  border-bottom: 1px solid #e0e0e0;
  overflow-x: auto;
}

.detail-tab-item {
  padding: 12px 16px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  white-space: nowrap;
  transition: all 0.3s;
}

.detail-tab-item.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

.detail-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.detail-section {
  height: 100%;
}

.detail-table-wrapper {
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.detail-table thead th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 600;
  padding: 12px 8px;
  border-bottom: 2px solid #e0e0e0;
  text-align: center;
  position: sticky;
  top: 0;
  z-index: 1;
}

.detail-table tbody td {
  padding: 10px 8px;
  border-bottom: 1px solid #eaeaea;
  text-align: center;
}

.history-group {
  margin-bottom: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  padding: 16px;
}

.history-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  display: block;
}

.history-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  background: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.history-person,
.history-date {
  font-size: 12px;
  color: #666;
}

.history-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8px;
}

/* 高亮行样式 - 根据修改次数显示不同深度 */
.highlighted-row-light {
  background-color: rgba(82, 196, 26, 0.15) !important;
  cursor: pointer;
  border-left: 3px solid rgba(82, 196, 26, 0.6);
}

.highlighted-row-medium {
  background-color: rgba(82, 196, 26, 0.25) !important;
  cursor: pointer;
  border-left: 3px solid rgba(82, 196, 26, 0.8);
}

.highlighted-row-heavy {
  background-color: rgba(82, 196, 26, 0.35) !important;
  cursor: pointer;
  border-left: 3px solid rgba(82, 196, 26, 1);
  font-weight: 600;
}

/* 保持原有的高亮行样式作为备用 */
.highlighted-row {
  background-color: rgba(82, 196, 26, 0.2) !important;
  cursor: pointer;
}

/* 当前选中的历史记录高亮样式 */
.current-highlight {
  background-color: rgba(64, 158, 255, 0.2) !important;
  border-left: 4px solid #409eff;
  animation: highlight-pulse 2s infinite;
}

@keyframes highlight-pulse {
  0% { background-color: rgba(64, 158, 255, 0.1); }
  50% { background-color: rgba(64, 158, 255, 0.3); }
  100% { background-color: rgba(64, 158, 255, 0.1); }
}

/* 高亮提示文本样式 */
.highlight-tip {
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 12px;
  font-size: 14px;
  border-left: 4px solid #67c23a;
}

/* 位置按钮样式 */
.location-btn {
  background-color: #409eff;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  margin: 0 4px;
}

.location-btn:hover {
  background-color: #66b1ff;
}

/* 位置模态框样式 */
.location-modal, .image-modal {
  background: white;
  border-radius: 8px;
  width: 80vw;
  max-width: 600px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.location-modal-header, .image-modal-header {
  position: relative;
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: center;
}

.location-modal-title, .image-modal-title {
  font-size: 18px;
  font-weight: 600;
}

.image-container {
  padding: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.image-swiper {
  width: 100%;
  height: 400px;
}

/* 修改次数显示样式 */
.modification-count {
  background-color: #f56c6c;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
}

/* 定额编码链接样式 */
.de-code-link {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.3s;
}

.de-code-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.de-code-link:active {
  color: #3a8ee6;
}

/* 项目经理单元格样式 - 支持自动换行 */
.manager-cell {
  white-space: pre-wrap !important;
  word-wrap: break-word !important;
  word-break: break-all !important;
  line-height: 1.4 !important;
  max-width: 120px;
  padding: 8px 4px !important;
}
</style>
